package com.study.service;

import com.spring.BeanPostProcessor;
import com.spring.Component;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

@Component
public class StudyBeanPostProcessor implements BeanPostProcessor {
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws Exception {
//        System.out.println("bean初始化前");
//        if(beanName.equals("memberService")){
//            ((MemberService)bean).setBeanName("你好！");
//        }
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws Exception {
//        System.out.println("初始化后");
        if("tmsService".equals(beanName)){
            //生成代理对象
            Object proxyInstance = Proxy.newProxyInstance(StudyBeanPostProcessor.class.getClassLoader(),
                    bean.getClass().getInterfaces(),
                    new InvocationHandler() {
                        @Override
                        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                            System.out.println("AOP代理逻辑!");
                            //然后在执行真正的类的方法 比如执行TmsService的test()方法
                            return method.invoke(bean, args);
                        }
                    });

            return proxyInstance;
        }
        return bean;
    }
}
